package com.kaifamiao.high.reflect;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * @author lucien-ma
 * @date 2021/9/27
 * @apiNote
 */
public class DBUtils<T> implements JDBCHelper<T> {

    private static String driver;
    private static String url;
    private static String username;
    private static String password;

    private static Connection connection;
    private static PreparedStatement preparedStatement;
    private static ResultSet resultSet;

    static {
        // 读取配置文件
        Properties properties = new Properties();
        InputStream inputStream = DBUtils.class.getClassLoader().getResourceAsStream("db.properties");
        try {
            properties.load(inputStream);
            // 赋值
            driver = properties.getProperty("driver");
            url = properties.getProperty("url");
            username = properties.getProperty("username");
            password = properties.getProperty("password");
            // 加载数据库驱动
            Class.forName(driver);
        } catch (IOException e) {
            e.printStackTrace();
            System.err.println("加载数据库配置文件失败");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            System.err.println("加载数据库驱动失败");
        }
    }

    /**
     * 获取连接
     * @return
     */
    private Connection getConnection(){
        try {
            if (connection == null) {
                connection = DriverManager.getConnection(url, username, password);
            }
        } catch (SQLException e) {
            e.printStackTrace();
            System.err.println("获取连接失败");
        }
        return connection;
    }

    /**
     * 关闭资源
     */
    public void close() {
        try {
            if (resultSet != null) {
                resultSet.close();
            }
            if (preparedStatement != null) {
                preparedStatement.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 查询并返回结果集
     * @param sql
     * @param params
     * @return
     */
    private ResultSet executeQuery(String sql, Object... params) {
        // 获取连接
        getConnection();
        // 获取 sql 执行对象
        try {
            preparedStatement = connection.prepareStatement(sql);
            // 设置参数
            setParam(params);
            return preparedStatement.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 增删改
     * @param sql
     * @param params
     * @return
     */
    private int executeUpdate(String sql, Object... params) {
        // 获取连接
        getConnection();
        // 获取 sql 执行对象
        try {
            preparedStatement = connection.prepareStatement(sql);
            // 设置参数
            setParam(params);
            // 执行并返回结果
            return preparedStatement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return -1;
    }

    /**
     * 为SQL中的占位符赋值
     * @param params
     */
    private void setParam(Object[] params) {
        if (params != null) {
            for (int i = 0; i < params.length; i++) {
                try {
                    preparedStatement.setObject(i+1, params[i]);
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public List<T> selectList(String sql, Class clazz, Object... params) {
        List<T> list = new ArrayList<>();
        // 查询结果集
        ResultSet resultSet = executeQuery(sql, params);
        try {
            // 遍历结果集
            while (resultSet.next()) {
                // 解析数据
                Object object = parseData(resultSet, clazz);
                // 添加到集合
                list.add((T) object);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 解析结果集
     * @param resultSet
     * @param clazz
     * @return
     */
    private T parseData(ResultSet resultSet, Class clazz) {
        try{
            // 反射创建对象
            Object object = clazz.getConstructor(null).newInstance(null);
            // 获取元数据
            ResultSetMetaData metaData = resultSet.getMetaData();
            // 获取列数
            int columnCount = metaData.getColumnCount();
            for (int i = 1; i <= columnCount; i++) {
                String columnLabel = metaData.getColumnLabel(i);
                Field[] fields = clazz.getDeclaredFields();
                // 遍历对象属性
                for (Field field : fields) {
                    if (field.getName().equals(columnLabel)) {
                        // 能匹配上就设值
                        field.setAccessible(true);
                        field.set(object, resultSet.getObject(i));
                    }
                }
            }
            return (T) object;
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }


    @Override
    public T selectOne(String sql, Class clazz, Object... params) {
        return selectList(sql, clazz, params).get(0);
    }

    @Override
    public int insert(String sql, Object... params) {
        return executeUpdate(sql, params);
    }

    @Override
    public int update(String sql, Object... params) {
        return executeUpdate(sql, params);
    }

    @Override
    public int delete(String sql, Object... params) {
        return executeUpdate(sql, params);
    }
}
